package com.future.message.Service.Impl;

import com.future.message.Mapper.IndexMapper;
import com.future.message.Mapper.RelevantReportMapper;
import com.future.message.Mapper.UserMapper;
import com.future.message.Service.FileService;
import com.future.message.Service.IndexService;
import com.future.message.Utils.ResponseResult;
import com.future.message.Utils.Utils;
import com.future.message.pojo.Index;
import com.future.message.pojo.RelevantReport;
import com.future.message.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class IndexServiceImpl implements IndexService {
    @Resource
    IndexMapper indexMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    RelevantReportMapper relevantReportMapper;
    @Resource
    FileService fileService;

    @Override
    public ResponseResult addOneIndex(String indexName) {
        Date date=new Date();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date1= simpleDateFormat.format(date);
        Index index=new Index();
        index.setIndexName(indexName);
        index.setIndexNowGrade(1);
        index.setSubmitTime(date1);
        index.setIndexFatherId(0);
        indexMapper.addIndex(index);
        return ResponseResult.success("添加一级指标成功",index);
    }

    @Override
    public ResponseResult addTwoIndex(String indexName, Integer indexFatherId) {
        Index index1=indexMapper.findIndexById(indexFatherId);
        if (index1 == null) {
            return ResponseResult.error("父指标不存在");
        }
        Date date=new Date();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date1= simpleDateFormat.format(date);
        Index index=new Index();
        index.setIndexFatherId(indexFatherId);
        index.setIndexName(indexName);
        index.setIndexNowGrade(2);
        index.setSubmitTime(date1);
        indexMapper.addIndex(index);
        return ResponseResult.success("添加二级指标成功",index);
    }

    @Override
    public ResponseResult addThreeIndex(String indexName, Integer indexFatherId) {
        Index index1=indexMapper.findIndexById(indexFatherId);
        if (index1 == null) {
            return ResponseResult.error("父指标不存在");
        }
        Date date=new Date();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date1= simpleDateFormat.format(date);
        Index index=new Index();
        index.setIndexFatherId(indexFatherId);
        index.setIndexName(indexName);
        index.setIndexNowGrade(3);
        index.setSubmitTime(date1);
        indexMapper.addIndex(index);
        return ResponseResult.success("添加三级指标成功",index);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deleteIndexById(Integer indexId) {
        Index index= indexMapper.findIndexById(indexId);
        if (index == null) {
            return ResponseResult.error("该指标不存在");
        }
        Integer arr[]={indexId};
        relevantReportMapper.deleteByThirdIndexId(arr);
        indexMapper.deleteIndexById(indexId);
        return ResponseResult.success("删除成功");
    }

    @Override
    public ResponseResult updateIndex(String content,Integer indexId) {
        Index index2= indexMapper.findIndexById(indexId);
        if (index2 == null) {
            return ResponseResult.error("该指标不存在");
        }
        indexMapper.updateIndex(content, indexId);
        Index index1=indexMapper.findIndexById(indexId);
        return ResponseResult.success("修改成功",index1);
    }

    @Override
    public ResponseResult findIndexById(Integer indexId) {
        Index index= indexMapper.findIndexById(indexId);
        if (index == null) {
            return ResponseResult.error("该指标不存在");
        }
        return ResponseResult.success("查找成功",index);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deleteIndexList(Integer[] indexId,Integer indexNowGrade) {
        if(indexNowGrade==1){//如果为一级指标
            for(int x:indexId){
                List<RelevantReport> relevantReportList=relevantReportMapper.findRelevantReportByFirstIndexId(x);//查询一级指标的填报关联
                List<Integer> c= relevantReportList.stream().map(RelevantReport::getRelevantReportId).collect(Collectors.toList());//将集合转化为一列id
//                System.out.println(c);
                if(!c.isEmpty()){relevantReportMapper.deleteRelevantLists(c);}
//                System.out.println(x);
                Integer[] i= indexMapper.findIndexesByIndexFatherId(x);//根据父指标id批量查询子指标--查二级
                for(int y:i){
                    List<RelevantReport> relevantReportLists=relevantReportMapper.findRelevantReportBySecondIndexId(y);
                    List<Integer> d= relevantReportLists.stream().map(RelevantReport::getRelevantReportId).collect(Collectors.toList());//将List集合转化为一列id
                    if(!d.isEmpty()){relevantReportMapper.deleteRelevantLists(d);}
                    Integer []j=indexMapper.findIndexesByIndexFatherId(y);//根据父指标id批量查询子指标---查三级
                        for(int z:j){
                            List<RelevantReport> relevantReportListss=relevantReportMapper.findRelevantReportByThirdIndexId(z);
                            List<Integer> e= relevantReportListss.stream().map(RelevantReport::getRelevantReportId).collect(Collectors.toList());//将List集合转化为一列id
                            if(!e.isEmpty()){relevantReportMapper.deleteRelevantLists(e);}
                            fileService.deleteIndexFilesByIndexId(z);
                            indexMapper.deleteIndexById(z);//删除三级指标
                        }
                    indexMapper.deleteIndexById(y);//删除二级指标
                }
            }
            indexMapper.deleteIndexList(indexId);//删除一级指标
        }

        if(indexNowGrade==2){
            for(int x:indexId){
                List<RelevantReport> relevantReportLists=relevantReportMapper.findRelevantReportBySecondIndexId(x);
                List<Integer> d= relevantReportLists.stream().map(RelevantReport::getRelevantReportId).collect(Collectors.toList());//将List集合转化为一列id
                if(!d.isEmpty()){relevantReportMapper.deleteRelevantLists(d);}
                Integer[] i= indexMapper.findIndexesByIndexFatherId(x);
                for(int y:i){
                    List<RelevantReport> relevantReportListss=relevantReportMapper.findRelevantReportByThirdIndexId(y);
                    List<Integer> e= relevantReportListss.stream().map(RelevantReport::getRelevantReportId).collect(Collectors.toList());//将List集合转化为一列id
                    if(!e.isEmpty()){relevantReportMapper.deleteRelevantLists(e);}
                    fileService.deleteIndexFilesByIndexId(y);
                    indexMapper.deleteIndexById(y);
                }
            }
            indexMapper.deleteIndexList(indexId);
        }

        if(indexNowGrade==3){
            for(int x:indexId){
                fileService.deleteIndexFilesByIndexId(x);
            }
            relevantReportMapper.deleteByThirdIndexId(indexId);
            indexMapper.deleteIndexList(indexId);
        }
        return ResponseResult.success("批量删除成功,子指标连带删除");
    }

    @Override
    public ResponseResult findAllIndexByIndexNowGrade(Integer indexNowGrade, Integer indexFatherId) {
//        Index index=indexMapper.findIndexById(indexFatherId);
//        if (index == null) {
//            return ResponseResult.error("父指标不存在");
//        }
       List<Index> indexList= indexMapper.findAllIndexByIndexNowGrade(indexNowGrade, indexFatherId);
        return ResponseResult.success("查找成功",indexList);
    }

    @Override
    public ResponseResult findIndexByUserIdAndIndexNowGrade(Integer userId, Integer indexNowGrade, Integer indexFatherId) {
        User user= userMapper.findUserById(userId);
        if (user == null) {
            return ResponseResult.error("该用户不存在");
        }
//        Index index=indexMapper.findIndexById(indexFatherId);
//        if (index == null) {
//            return ResponseResult.error("该指标不存在");
//        }
        List<Index> indexList= indexMapper.findIndexByUserIdAndIndexNowGrade(userId,indexNowGrade, indexFatherId);
        return ResponseResult.success("查找成功",indexList);
    }

    @Override
    public ResponseResult updateData(Integer thirdIndexId, MultipartFile[] data) {
        Index index= indexMapper.findIndexById(thirdIndexId);
        if(index==null){
            return ResponseResult.error("不存在该三级指标");
        }
        Integer grade= indexMapper.findGradeByIndexId(thirdIndexId);
        if(grade!=3){
            return ResponseResult.error("必须是三级指标才能上传模板");
        }
        fileService.batchUploadIndexFile(data,thirdIndexId);
        ArrayList<String> arrayList=new ArrayList<>();
        if(index.getData()!=null){
            String[] oldSrc= Utils.split(index.getData());
            for(String s:oldSrc){
                if(s!=null&&s!=""){
                    arrayList.add(s);
                }
            }
        }
        log.info(arrayList.toString());
        if(data!=null){
            for(MultipartFile x: data){
                if(arrayList.contains(x.getOriginalFilename())){
                    break;
                }
                arrayList.add(x.getOriginalFilename());
                String fileF = x.getOriginalFilename().substring(x.getOriginalFilename().lastIndexOf("."), x.getOriginalFilename().length());//文件后缀
                if ((fileF.equals(".asp") || fileF.equals(".php") ||
                        fileF.equals(".aspx") || fileF.equals(".cgi")||
                        fileF.equals(".exe")||fileF.equals(".html")||
                        fileF.equals(".htm")||fileF.equals(".jsp"))){
                    arrayList.remove(x.getOriginalFilename());
                }
            }
        }
        log.info(arrayList.toString());
        indexMapper.updateData(thirdIndexId, arrayList.toString());
        return ResponseResult.success("文件上传成功");
    }

    @Override
    public ResponseResult extendsIndex(String year) {
        Thread thread=new Thread();

        List<Index> indexList=indexMapper.findAllIndexByYear(year);
        List<Integer> integers=indexList.stream().map(Index::getIndexId).collect(Collectors.toList());
        Date date=new Date();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date1=simpleDateFormat.format(date);
        HashMap<Integer,Integer> hashMap=new HashMap<>();
        for(Integer i:integers){
            Index index=indexMapper.findIndexById(i);
            if(index.getIndexNowGrade()==1){
                Index index1=new Index();
                index1.setIndexName(index.getIndexName());
                index1.setIndexFatherId(index.getIndexFatherId());
                index1.setIndexNowGrade(index.getIndexNowGrade());
                index1.setSubmitTime(date1);
                index1.setData(index.getData());
                indexMapper.addExtendsIndex(index1);
                hashMap.put(i,index1.getIndexId());
            }
            if(index.getIndexNowGrade()==2){
                if(hashMap.get(index.getIndexFatherId())!=null){
                    Index index1=new Index();
                    index1.setIndexName(index.getIndexName());
                    index1.setIndexFatherId(hashMap.get(index.getIndexFatherId()));
                    index1.setIndexNowGrade(index.getIndexNowGrade());
                    index1.setSubmitTime(date1);
                    index1.setData(index.getData());
                    indexMapper.addExtendsIndex(index1);
                    hashMap.put(i,index1.getIndexId());
                }
            }
            if(index.getIndexNowGrade()==3){
                if(hashMap.get(index.getIndexFatherId())!=null){
                    Index index1=new Index();
                    index1.setIndexName(index.getIndexName());
                    index1.setIndexFatherId(hashMap.get(index.getIndexFatherId()));
                    index1.setIndexNowGrade(index.getIndexNowGrade());
                    index1.setSubmitTime(date1);
                    index1.setData(index.getData());
                    indexMapper.addExtendsIndex(index1);
                    fileService.extendsFile(i,index1.getIndexId());
                    hashMap.put(i,index1.getIndexId());
                }
            }
        }
        return ResponseResult.success("继承"+year+"年的指标成功");
    }

    @Override
    public ResponseResult findAllIndexByIndexNowGradeAndYear(Integer indexNowGrade, Integer indexFatherId, String year) {
        List<Index> indexList= indexMapper.findAllIndexByIndexNowGradeAndYear(indexNowGrade, indexFatherId,year);
        return ResponseResult.success("查找成功",indexList);
    }


}
